// configmap.go
package controllers

import (
	"log"
	m "myk8s/models"
	"strings"

	//"github.com/tidwall/gjson"

	beego "github.com/beego/beego/v2/server/web"
)

type ConfigMapController struct {
	beego.Controller
}

func (this *ConfigMapController) List() {
	clusterId := this.GetString("clusterId")
	nameSpace := this.GetString("nameSpace")
	configmapName := this.GetString("configmapName")

	labels := this.GetString("labels")
	labelsKV := strings.Split(labels, ":")
	var labelsKey, labelsValue string
	if len(labelsKV) == 2 {
		labelsKey = labelsKV[0]
		labelsValue = labelsKV[1]
	}
	cmList, err := m.CmList(clusterId, nameSpace, configmapName, labelsKey, labelsValue)
	msg := "success"
	code := 0
	count := len(cmList)
	if err != nil {
		log.Println(err)
		msg = err.Error()
		code = -1
	}
	this.Data["json"] = &map[string]interface{}{"code": code, "msg": msg, "count": count, "data": &cmList}
	this.ServeJSON()
}

func (this *ConfigMapController) Create() {
	clusterId := this.GetString("clusterId")
	code := 0
	msg := "success"
	err := m.CmCreate(clusterId, this.Ctx.Input.RequestBody)
	if err != nil {
		code = -1
		msg = err.Error()
		log.Printf("[ERROR] configmap Create Fail:%s\n", err)
	}
	this.Data["json"] = &map[string]interface{}{"code": code, "msg": msg}
	this.ServeJSON()
}

func (this *ConfigMapController) ModifyByYaml() {
	clusterId := this.GetString("clusterId")
	code := 0
	msg := "success"
	bodyByte := []byte(strings.ReplaceAll(string(this.Ctx.Input.RequestBody), "%25", "%"))
	err := m.CmYamlModify(clusterId, bodyByte)
	if err != nil {
		code = -1
		msg = err.Error()
		log.Printf("[ERROR] configmap ModifyByYaml Fail:%s\n", err)
	}
	this.Data["json"] = &map[string]interface{}{"code": code, "msg": msg}
	this.ServeJSON()
}

func (this *ConfigMapController) Yaml() {
	clusterId := this.GetString("clusterId")
	namespace := this.GetString("nameSpace")
	configmapName := this.GetString("configmapName")

	yamlStr, _ := m.GetCmYaml(clusterId, namespace, configmapName)
	this.Ctx.WriteString(yamlStr)
}
